package com.thon.controller.rest;

import java.util.Date;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

import org.hibernate.HibernateException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import com.thon.dao.util.Page;
import com.thon.entity.project.Project;
import com.thon.entity.project.ProjectCategory;
import com.thon.entity.project.Region;
import com.thon.entity.user.Charitarian;
import com.thon.entity.user.Coupon;
import com.thon.entity.user.FinanceView;
import com.thon.entity.user.FundDetail;
import com.thon.entity.user.Institution;
import com.thon.entity.user.User;
import com.thon.service.project.ProjectCategoryService;
import com.thon.service.project.ProjectService;
import com.thon.service.project.RegionService;
import com.thon.service.system.RolesService;
import com.thon.service.user.CharitarianService;
import com.thon.service.user.CouponService;
import com.thon.service.user.FundDetailService;
import com.thon.service.user.InstitutionService;
import com.thon.service.user.UserService;

/**
 * @file SystemRestController.java
 * @author zhangyong
 * @email ZY1791317931@163.com
 * @date 2013年12月5日 下午14:20:40
 * @description 后台信息接口
 */
@Controller
@RequestMapping("/api/admin")
@SuppressWarnings({ "rawtypes", "unchecked" })
public class AdminRestController {
	@Autowired
	private UserService userService;
	@Autowired
	private InstitutionService institutionService;
	@Autowired
	private CharitarianService charitarianService;
	@Autowired
	private ProjectService projectService;
	@Autowired
	private ProjectCategoryService projectCategoryService;
	@Autowired
	private RegionService regionService;
	@Autowired
	private FundDetailService fundDetailService;
	@Autowired
	private CouponService couponService;
	@Autowired
	private RolesService rolesService;

	// 根据用户角色分页获取用户列表
	@RequestMapping(value = "/user/list", method = RequestMethod.GET)
	public ResponseEntity<HttpEntity> userList(
			@RequestParam(value = "roles", required = true) String roles,
			@RequestParam(value = "p", defaultValue = "1") int p,
			@RequestParam(value = "s", defaultValue = "10") int s) {

		Page<User> page = userService.findUserPage(roles, p, s);

		return new ResponseEntity(page, HttpStatus.CREATED);
	}
	
	// 添加新用户
	@RequestMapping(value = "/user/add", method = RequestMethod.POST)
	public ResponseEntity<HttpEntity> addUser(@Valid @RequestBody User user) {
		userService.addUser(user);
		return new ResponseEntity(user, HttpStatus.OK);
	}
	
	//根据用户id修改用户角色
	@RequestMapping(value = "/user/update/role", method = {RequestMethod.GET,RequestMethod.POST})
	public ResponseEntity<?> updateUserRole(@RequestParam(value="id") int id,
											@RequestParam(value="role") String role){
		User user = userService.getUser(id);
		//user.setRoles(role);
		userService.updateUser(user);
		return new ResponseEntity(true, HttpStatus.OK);
	}
	
	
	// 根据用户id修改用户信息
	@RequestMapping(value = "/user/update", method = RequestMethod.POST)
	public ResponseEntity<HttpEntity> updateUser(@Valid @RequestBody User user) {

		User oldUser = new User();
		oldUser = userService.getUser(user.getId());
		oldUser.setStatus(user.getStatus());
		if(user.getPlainPassword()!=null){
			oldUser.setPlainPassword(user.getPlainPassword());
		}
		oldUser.setLoginName(user.getLoginName());
		oldUser.setName(user.getName());
		oldUser.setEmail(user.getEmail());
		oldUser.setRoles(rolesService.read(user.getRoles().getId()));
		//oldUser.setFund(user.getFund());
		//oldUser.setRoles(user.getRoles());
		userService.updateUser(oldUser);
		return new ResponseEntity(oldUser, HttpStatus.OK);
	}
	
	//根据用户id删除用户
	@SuppressWarnings("finally")
	@RequestMapping(value="/user/delete",method=RequestMethod.POST)
	public ResponseEntity<HttpEntity> deleteUser(@RequestParam(value="uid",required=true)Integer userId){
		Integer status=0;
		try{
			userService.deleteUser(userId);
		}catch(Exception e){
			status=1;
		}finally{
			return new ResponseEntity(status,HttpStatus.OK);
		}
	}
	
	
	// 修改项目信息
	@RequestMapping(value = "/project/update", method = RequestMethod.POST)
	public ResponseEntity<HttpEntity> updateProject(@Valid @RequestBody Project project) {

		Project oldProject = new Project();
		oldProject = projectService.getProject(0, project.getId());
		oldProject.setStatus(project.getStatus());
		//oldProject.setProjectCategory(project.getProjectCategory());
		oldProject.setValidDays(project.getValidDays());
		oldProject.setContect(project.getContect());
		oldProject.setProjectOpen(project.getProjectOpen());
		oldProject.setProjectBenefit(project.getProjectBenefit());
		if(project.getStatus()==3){
			oldProject.setFundraisingDate(new Date());
		}
		if (oldProject.getStatus() == 6) {
			oldProject.setTags(null);
		}else {
			oldProject.setTags(project.getTags());
		}
		
		projectService.updateProject(oldProject);		
	
		return new ResponseEntity(oldProject, HttpStatus.OK);
	}
	
	// 修改机构信息
	@RequestMapping(value = "/institution/update", method = RequestMethod.POST)
	public ResponseEntity<HttpEntity> updateInstitution(@Valid @RequestBody Institution institution) {
		Byte passed = 2;
		Byte check = 1;
		Byte refusal = 3;
		Institution oldInstitution = new Institution();
		
		oldInstitution = institutionService.getInstitutionByUser(institution.getUser().getId());
		oldInstitution.setDescription(institution.getDescription());
		oldInstitution.setStatus(institution.getStatus());
		institutionService.updateInstitution(oldInstitution);
		if (institution.getStatus().equals(passed)) {
			User oldUser = new User();
			oldUser = userService.getUser(institution.getUser().getId());
			//oldUser.setRoles("institution");
			userService.updateUser(oldUser);
		}else if (institution.getStatus().equals(check) || institution.getStatus().equals(refusal)) {
			User oldUser = new User();
			oldUser = userService.getUser(institution.getUser().getId());
			//oldUser.setRoles("user");
			userService.updateUser(oldUser);
		}
		return new ResponseEntity(oldInstitution, HttpStatus.OK);
	}

	// 修改机构信息
	@RequestMapping(value = "/charitarian/update", method = RequestMethod.POST)
	public ResponseEntity<HttpEntity> updateCharitarian(@Valid @RequestBody Charitarian charitarian) {
		Byte passed = 2;
		Byte check = 1;
		Byte refusal = 0;
		Charitarian oldCharitarian = new Charitarian();
		
		oldCharitarian = charitarianService.getCharitarian(charitarian.getId());
		oldCharitarian.setStatus(charitarian.getStatus());
		oldCharitarian.setNickName(charitarian.getNickName());
		oldCharitarian.setSinaWeibo(charitarian.getSinaWeibo());
		oldCharitarian.setTencentWeibo(charitarian.getTencentWeibo());
		charitarianService.updateCharitarian(oldCharitarian);
		if (charitarian.getStatus().equals(passed)) {
			User oldUser = new User();
			oldUser = userService.getUser(charitarian.getUser().getId());
			//oldUser.setRoles("charitarian");
			userService.updateUser(oldUser);
		}else if (charitarian.getStatus().equals(check) || charitarian.getStatus().equals(refusal)) {
			User oldUser = new User();
			oldUser = userService.getUser(charitarian.getUser().getId());
			//oldUser.setRoles("user");
			userService.updateUser(oldUser);
		}
		return new ResponseEntity(oldCharitarian, HttpStatus.OK);
	}
	/**
	 * 根据不同条件(权限、状态、地区等)筛选用户
	 * 
	 * @param by
	 *            可选值:1、roles(权限) 2、status(用户审核状态) 3、address(地区)
	 * @param condition
	 *            (对应category三种可选值)
	 * @param p
	 *            (页码)
	 * @param s
	 *            (页大小)
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "/user/{by}", method = RequestMethod.GET)
	public ResponseEntity<HttpEntity> listUserPage(
			@PathVariable(value = "by") String by,
			@RequestParam(value = "condition", required = true) String condition,
			@RequestParam(value = "p", defaultValue = "1") int p,
			@RequestParam(value = "s", defaultValue = "10") int s) {

		Page<User> page = userService.listUserPage(by, condition, p, s);
		return new ResponseEntity(page, HttpStatus.CREATED);
	}

	/**
	 * 按项目状态或分类分页获取项目
	 * 
	 * @param by
	 *            可选值:1、status(项目状态:1：预审、2：众审、3：众酬、4：执行、5：完结、6：失败)
	 *            2、category(项目类型:1:环境 2:教育 3:妇女 4:动物保护 5:老人 6:扶贫 7: 残疾人 8:动物保护
	 *            根据数据库中给定值)
	 * @param intValue
	 *            (by对应的两种情况对应的值)
	 * @param p
	 *            (页码)
	 * @param s
	 *            (页大小)
	 * @return
	 */
	@RequestMapping(value = "/project/{by}/list", method = RequestMethod.POST)
	public ResponseEntity<HttpEntity> listProjectByStatus(
			@PathVariable(value = "by") String by,
			@RequestParam(value = "status",defaultValue = "3")int status,
			@RequestParam(value = "intValue", required = true) int intValue,
			@RequestParam(value = "p", defaultValue = "1") int p,
			@RequestParam(value = "s", defaultValue = "10") int s) {

		Page<Project> page = null;
		if (by.equals("status"))
			page = projectService.findProjects(-1,intValue, p, s);
		else if (by.equals("category"))
			page = projectService.findProjectByCategory(intValue, p,s,-1,status);
		return new ResponseEntity(page, HttpStatus.CREATED);
	}

	/**
	 * 根据项目状态或者项目分类修改项目信息
	 * @param by
	 *            可选值:1、status 2、category
	 * @param pid
	 *            (项目id)
	 * @param intValue
	 *            (by对应的两种情况下的值)
	 * @return
	 */
	@RequestMapping(value = "/project/{by}/update", method = RequestMethod.POST)
	public ResponseEntity<HttpEntity> updateProjectStatus(
			@PathVariable(value = "by") String by,
			@RequestParam(value = "pid", required = true) Integer pid,
			@RequestParam(value = "intValue", required = true) int intValue) {

		Project project = projectService.getProject(-1,pid);
		if (by.equals("status"))
			project.setStatus(intValue);
		else if (by.equals("category")) {
			ProjectCategory projectCategory = projectCategoryService
					.getProjectCategory(intValue);
			project.setProjectCategory(projectCategory);
		}
		projectService.updateProject(project);
		return new ResponseEntity(project, HttpStatus.OK);
	}

	// 按项目状态统计项目数量
	@RequestMapping(value = "/project/count", method = RequestMethod.GET)
	public ResponseEntity<HttpEntity> countProjectByStatus(
			@RequestParam(value = "status", required = true) int status) {

		Long count = projectService.countProject("status",status);
		return new ResponseEntity(count, HttpStatus.OK);
	}

	// 增加项目分类
	@RequestMapping(value = "/project/projectcategory/add", method = RequestMethod.POST)
	public ResponseEntity<HttpEntity> addProjectCategory(
			@Valid @RequestBody ProjectCategory projectCategory) {

		projectCategoryService.addProjectCategory(projectCategory);
		return new ResponseEntity(true, HttpStatus.OK);
	}

	// 分页获取地理位置列表
	@RequestMapping(value = "/region/list", method = RequestMethod.GET)
	public ResponseEntity<HttpEntity> listRegions(
			@RequestParam(value = "p", required = false) int p,
			@RequestParam(value = "s", required = false) int s) {

		Page<Region> page = regionService.findRegionPage(p, s);
		return new ResponseEntity(page, HttpStatus.CREATED);
	}

	// 根据地理位置id修改地理位置信息
	@RequestMapping(value = "/region/update", method = RequestMethod.POST)
	public ResponseEntity<HttpEntity> updateRegion(
			@Valid @RequestBody Region region) {

		regionService.updateRegion(region);
		return new ResponseEntity(region, HttpStatus.OK);
	}

	//增加地理位置
	@RequestMapping(value = "/region/add", method = RequestMethod.POST)
	public ResponseEntity<HttpEntity> addRegion(@Valid @RequestBody Region region){
		
		regionService.addRegion(region);
		return new ResponseEntity(region, HttpStatus.OK);
	}
	
	//充值记录列表
	@RequestMapping(value = "/deposit/list", method = RequestMethod.GET)
	public ResponseEntity<HttpEntity> listFundDetail(
			@RequestParam(value="actionType",required=true)int actionType,
			@RequestParam(value = "p", required = false) int p,
			@RequestParam(value = "s", required = false) int s){
		
		Page<FundDetail> page=fundDetailService.findFundDetails(p, s,actionType);
		return new ResponseEntity(page, HttpStatus.OK);
	}
	
	//用户财务明细列表
	@RequestMapping(value = "/finance/list", method = RequestMethod.GET)
	public ResponseEntity<HttpEntity> listFinca(
			@RequestParam(value = "p", defaultValue="1") int p,
			@RequestParam(value = "s", defaultValue="10") int s){
		
		Page<FinanceView> page=fundDetailService.findFinace(p, s);
		return new ResponseEntity(page, HttpStatus.OK);
	}
	
	//发放优惠券
	@RequestMapping(value = "/coupon/provide", method = RequestMethod.POST)
	public ResponseEntity<?> provideCoupon(@RequestParam(value = "id", required = true)int id,
										   @RequestParam(value = "project", required = true)int projectId,
										   @Valid User user,
										   @Valid Coupon coupon,
										   @RequestParam(value = "num")Integer num) {
		Date today = new Date();
		for ( int i=0; i<num; i++) {
			Coupon c = new Coupon();
			Project project = new Project();
			project.setId(projectId);
			c.setCouponStatus("1");
			c.setCouponNo(today.toString()+user.getId()+i);
			c.setCouponValue(coupon.getCouponValue());
			c.setCreatedDate(today);
			c.setOverdueDate(coupon.getOverdueDate());
			c.setCouponExplain(coupon.getCouponExplain());
			c.setMemo(coupon.getMemo());
			c.setUser(userService.getUser(user.getId()));
			c.setCreated_by(userService.getUser(id));
			c.setProject(project);
			couponService.save(c);
		}
		return new ResponseEntity(true, HttpStatus.OK);
	}
	
	//确认申请
	@RequestMapping(value = "/confirmCash", method = RequestMethod.POST)
	public ResponseEntity<HttpEntity> comfirmCash(@RequestParam("Fund_no") String FundNo) {
		
		FundDetail fundDetail = fundDetailService.getFundDetail(FundNo);
		if(fundDetail==null)
			return new ResponseEntity("no_fundDetial", HttpStatus.OK);
		
		User user = fundDetail.getUser();
		if(user==null)
			return new ResponseEntity("no_user", HttpStatus.OK);
		
		if(user.getFund()-fundDetail.getAmount()<0)
			return new ResponseEntity("no_enough_cash", HttpStatus.OK);
		
		user.setFund(user.getFund()-fundDetail.getAmount());
		
        userService.updateUser(user);
		
		fundDetail.setActionType(6);
		
		fundDetailService.updateFundDetail(fundDetail);
		
		return new ResponseEntity("success", HttpStatus.OK);
	}
	
	//确认申请
	@RequestMapping(value = "/refuseCash", method = RequestMethod.POST)
	public ResponseEntity<HttpEntity> refuseCash(@RequestParam("Fund_no") String FundNo) {
		
		FundDetail fundDetail = fundDetailService.getFundDetail(FundNo);
		if(fundDetail==null)
			return new ResponseEntity("no_fundDetial", HttpStatus.OK);
		
		User user = fundDetail.getUser();
		if(user==null)
			return new ResponseEntity("no_user", HttpStatus.OK);		
		
		fundDetail.setActionType(7);
		
		fundDetailService.updateFundDetail(fundDetail);

		return new ResponseEntity("success", HttpStatus.OK);
	}
	//确认申请
	@RequestMapping(value = "/getLatestCash", method = RequestMethod.GET)
	public ResponseEntity<HttpEntity> getLatestCash(@RequestParam("uid") Integer uid) {
		FundDetail fundDetail;
		Page<FundDetail> fundDetailPage = fundDetailService.findFundDetailsByUser(uid,6,1,1);
		if(fundDetailPage.getTotalCount()==0)
		{		
				return new ResponseEntity(null, HttpStatus.OK);
			
		}
		else
			fundDetail = fundDetailPage.getResult().get(0);			

		return new ResponseEntity(fundDetail, HttpStatus.OK);
	}
}
